import 'package:aichat_flutter_wallet/module/module_wallet/provider/wallet_index_provider.dart';
import 'package:aichat_flutter_wallet/module_common/mpc_help/createWalletTool.dart';
import 'package:aichat_flutter_wallet/module_common/mpc_help/mpcManager.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:lib_database/lib_database.dart';
import 'package:lib_network/http_config.dart';
import 'package:lib_network/http_manager.dart';
import 'package:lib_util/lib_util.dart';

import '../../../kai_print.dart';
import '../../../module_common/bridge/native_channel_bridge.dart';
import '../../../module_common/network/http_api.dart';
import '../../../module_common/network/http_chain_list.dart';
import '../../../module_common/provider/wallet_info_provider.dart';
import '../../../module_common/widgets/header/page_assets_header.dart';
import 'package:animated_text_kit/animated_text_kit.dart';

import '../../../module_common/widgets/loading/small_loading.dart';
import '../../../module_common/widgets/public_tip/public_tip.dart';
//  重写
enum WalletCreationType { RECAST, GENERATE , OVERWRITE}

class PageUnderCreation extends StatefulWidget {
  // 私钥
  final String? pk;
  final String? path;
  final String? passphrase;
  final WalletCreationType type;
  final Future<List<String>> Function()? callBack;
  final int? version;

  PageUnderCreation(
      {super.key,
      this.pk,
      this.path,
      this.passphrase,
      this.callBack,
      this.version,
      this.type = WalletCreationType.GENERATE});

  @override
  _PageUnderCreationState createState() => _PageUnderCreationState();
}

class _PageUnderCreationState extends State<PageUnderCreation>
    with TickerProviderStateMixin {
  late AnimationController _controller;
  late AnimationController _animationController;
  late Animation<double> _progressAnimation;
  int index = 0;

  @override
  void initState() {
    super.initState();

    _animationController = AnimationController(
      duration: const Duration(milliseconds: 5000),
      vsync: this,
    );

    _progressAnimation = Tween<double>(begin: 0, end: 0.1).animate(
      CurvedAnimation(
        parent: _animationController,
        curve: Curves.easeInOut,
      ),
    );
    if (mounted) _animationController.forward();
    _controller = AnimationController(
      duration: const Duration(seconds: 2),
      vsync: this,
    )..repeat();

    // 判断 ；链丢失  重新 获取 配置 链的信息
  }

  // 设置顶部进度

  void setLoadingIndex() async {
    if (mounted)
      _animationController.duration = const Duration(milliseconds: 2000);
    if (mounted)
      _progressAnimation = Tween<double>(
              begin: _progressAnimation.value,
              end: _progressAnimation.value + 0.25)
          .animate(_animationController);
    if (mounted) _animationController.reset();
    if (mounted) _animationController.forward();
  }

  Future<bool> overwriteServerMPCUpload(forgingMPCResp fragmentation) async {
    try {
      if (fragmentation.mpcPieceC.length <= 0) {
        throw Exception('Algorithm generated wallet exception.');
      }
      // 上传服务器直接 成功 才生成 钱包
      Map<String, dynamic> params = {'cover': 1,'mpcSalt': fragmentation.mpcPieceC};
      var resp = await HttpManager().post(API.uploadOnePiece, params);
      if (resp!.code != HttpConfig().successCode) {
        throw Exception('Failed to upload private key.');
      }
      kaiPrint('upload success？  ： ${resp.data['result']}');
      if (resp.data['result'] == false) {
        throw Exception('Failed to upload private key.');
      }
      //上传服务器成功
      context.read<WalletInfoNotifier>().updateWalletServer();
      return true;
    } catch (e) {
      return false;
    }
  }

  Future<bool> callBackUpload(forgingMPCResp fragmentation, String salt) async {
    try {
      if (fragmentation.mpcPieceC.length <= 0) {
        throw Exception('Algorithm generated wallet exception.');
      }
      // 上传服务器直接 成功 才生成 钱包
      Map<String, dynamic> params = {'cover': 0,'mpcSalt': fragmentation.mpcPieceC};
      var resp = await HttpManager().post(API.uploadOnePiece, params);
      if (resp!.code != HttpConfig().successCode) {
        throw Exception('Failed to upload private key.');
      }
      kaiPrint('upload success？  ： ${resp.data['result']}');
      if (resp.data['result'] == false) {
        throw Exception('Failed to upload private key.');
      }
      kaiPrint('salt.toString()  ${salt.toString()}');
      Map<String, dynamic> paramsSalt = {
        'mpcSalt': salt.toString().isEmpty?'\        ':salt.toString(),
      };
      var result = await HttpManager().post(API.uploadMpcSalt, paramsSalt);
      if (resp.code != HttpConfig().successCode) {
        throw Exception('Failed to upload salt.');
      }
      kaiPrint('upload？  ： ${result!.data['isUpload']}');
      if (result.data['isUpload'] == false) {
        throw Exception('Failed to upload salt.');
      }
      if (result.data['isUpload'] == null) {
        throw Exception('Failed to upload salt.');
      }

      //上传服务器成功
      context.read<WalletInfoNotifier>().updateWalletServer();

      return true;
    } catch (e) {
      return false;
    }
  }

  // 初始化 创建 钱包
  void initCreatedWallet() async {
    try {
      // 获取 盐 的接口
      // 获取盐
      var salt = await SP().getRandomSalt();
      if (widget.pk != null) {
        // 原装 盐
        salt = widget.passphrase ?? '';
      } else {
        String? serverSalt = await HttpChainList().getSaltByUrl();
        // 新用户
        if (serverSalt == null) {
          salt = await SP().generateRandomSalt();
        } else {
          salt = serverSalt;
        }
      }
      await SP().setRandomSalt(salt);
      forgingMPCResp? fragmentation = null;
      if (widget.pk != null) {
        fragmentation = await mpcTool().useMnemonicForgingMPC(
            widget.pk!, salt, widget.path ?? ChainList.derivePathEVM);
      } else {
        fragmentation = await mpcTool().forgingMPC(salt.toString(), null);
      }
      if (fragmentation.mpcPieceC.isEmpty) {
        throw Exception('Algorithm generation failed');
      }
      // 判断是否上传 成功。 成功 存两片， 不成功存三片
      bool isUpload = await callBackUpload(fragmentation, salt.toString());
      String key = isUpload
          ? '${fragmentation.mpcPieceA},${fragmentation.mpcPieceB}'
          : '${fragmentation.mpcPieceA},${fragmentation.mpcPieceB},${fragmentation.mpcPieceC}';
      List<Chain> chains = ChainList().chains;
      if (chains.isEmpty) {
        throw Exception(
            'Failed to obtain chain basic configuration, please make sure the network is normal');
      }
      final userId = NativeChannelBridge.instance.appCommMsg?.userId ?? '';
      kaiPrint('key--------------------------- ${isUpload}');
      // 找到以前的 walletid 并重新覆盖
      final value = await createWalletTool().createWallet(key, chains, userId,
          walletName: "MPC Wallet A",
          isMPC: true,
          salt: salt.toString(),
          backup: widget.pk != null,
          isServerBackUp: isUpload);
      if (value.length <= 0) {
        throw Exception('Failed to generate wallet.Network configuration lost');
      }
      kaiPrint('initCreatedWallet-----------------');
      context.read<WalletInfoNotifier>().updateCurrentWallet(value[0]);
      context.read<WalletIndexProvider>().updateInfo();
      Navigator.of(context).pop(widget.pk == null ? "Success" : 'Cancel');
    } catch (e) {
      kaiPrint('生成钱包失败！ $e');
      Navigator.of(context).pop("Failed");
      Toast.show(context,
          status: '0',
          position: Dpositon.top,
          message: e.toString(),
          duration: const Duration(milliseconds: 4000));
    }
  }


  // 初始化 创建 钱包
  void initOverwriteWallet() async {
    try {
      // 获取 盐 的接口
      // 获取盐
      var salt = await SP().getRandomSalt();
      String? serverSalt = await HttpChainList().getSaltByUrl();
      // 新用户
      if (serverSalt != null) {
        salt = serverSalt;
      }
      List<String> pieceList = await widget.callBack!();
      if(pieceList.isEmpty || pieceList.length<2){
        throw Exception('The upgrade failed and mpc fragments were lost！');
      }
      forgingMPCResp? fragmentation  = await mpcTool().upgradeMPC(pieceList[0],pieceList[1],salt.toString());
      if (fragmentation.mpcPieceC.isEmpty) {
        throw Exception('Algorithm generation failed');
      }
      // 判断是否上传 成功。 成功 存两片， 不成功存三片
      bool isUpload = await overwriteServerMPCUpload(fragmentation);
      String key = isUpload
          ? '${fragmentation.mpcPieceA},${fragmentation.mpcPieceB}'
          : '${fragmentation.mpcPieceA},${fragmentation.mpcPieceB},${fragmentation.mpcPieceC}';
      List<Chain> chains = ChainList().chains;
      if (chains.isEmpty) {
        throw Exception(
            'Failed to obtain chain basic configuration, please make sure the network is normal');
      }
      final userId = NativeChannelBridge.instance.appCommMsg?.userId ?? '';
      kaiPrint('key--------------------------- ${isUpload}');
      final value = await createWalletTool().overwriteWallet(key, chains, userId,
          walletName: "MPC Wallet A",
          isMPC: true,
          salt: salt.toString(),
          backup: widget.pk != null,
          isServerBackUp: isUpload);
      if (value.length <= 0) {
        throw Exception('Failed to generate wallet.Network configuration lost');
      }
      kaiPrint('overwrite mpc successfully-----------------');
      context.read<WalletInfoNotifier>().updateCurrentWallet(value[0]);
      context.read<WalletIndexProvider>().updateInfo();
      Navigator.of(context).pop(widget.pk == null ? "Success" : 'Cancel');
    } catch (e) {
      kaiPrint('生成钱包失败！ $e');
      Navigator.of(context).pop("Failed");
      Toast.show(context,
          status: '0',
          position: Dpositon.top,
          message: e.toString(),
          duration: const Duration(milliseconds: 4000));
    }
  }

  // 重铸 钱包流程
  void initRecastWallet() async {
    try {
      if (widget.callBack != null) {
        List<String> isTrue = await widget.callBack!();
        if (isTrue.isEmpty) {
          throw Exception('Casting failed. Please recast the current wallet.');
        }
      } else {
        throw Exception('Please set the callback function first');
      }
      Navigator.of(context).pop("Success");
    } catch (e) {
      kaiPrint('wallet create failed！ $e');
      Navigator.of(context).pop("Failed");
      Toast.show(context,
          status: '0',
          position: Dpositon.top,
          message: e.toString(),
          duration: const Duration(milliseconds: 4000));
    }
  }

  void _handleTap() {
    if (mounted)
      setState(() {
        index++;
      });
  }

  @override
  void dispose() {
    _controller.dispose();
    _animationController.dispose();
    // TODO: implement dispose
    super.dispose();
  }

  Widget bottomNavigationBar() {
    return Container(
      // color: Color.fromRGBO(255, 255, 255, 1),
      padding: EdgeInsets.only(
        left: 20.w,
        right: 20.w,
        bottom: 54.w,
      ),
      child: Row(
        children: [
          SmallLoading(
            width: 16.w,
            height: 16.w,
          ),
          SizedBox(
            width: 7.w,
          ),
          Expanded(
              child: Text(
            'MPC Wallet is Ready',
            style: TextStyle(
                fontSize: 12.sp, color: Color.fromRGBO(106, 106, 106, 1)),
          ))
        ],
      ),
    );
  }

  Widget createWalletWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(
          height: 70,
        ),
        Stack(
          children: [
            Opacity(
              opacity: index > 0 ? 1 : 0, // 设置透明度值，范围从 0.0 到 1.0
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    padding: EdgeInsets.only(left: 20, right: 20),
                    child: Text(
                      'Kai will create your MPC wallet via',
                      style: const TextStyle(
                        fontWeight: FontWeight.w600,
                        fontSize: 18,
                        height: 1.33,
                        color: Color.fromRGBO(193, 193, 193, 1),
                      ),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(left: 20, right: 20),
                    child: Text(
                      'dual-entropy obfuscation',
                      style: const TextStyle(
                        fontWeight: FontWeight.w600,
                        fontSize: 18,
                        height: 1.33,
                        color: Color.fromRGBO(193, 193, 193, 1),
                      ),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(left: 20, right: 20),
                    child: Text(
                      'algorithm',
                      style: const TextStyle(
                        fontWeight: FontWeight.w600,
                        fontSize: 18,
                        height: 1.33,
                        color: Color.fromRGBO(193, 193, 193, 1),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: index == 0 ? 30 : 20,
                  ),
                ],
              ),
            ),
            Positioned(
                left: 0,
                top: 0,
                right: 0,
                bottom: 0,
                child: Visibility(
                    visible: index == 0,
                    child: Container(
                      padding: EdgeInsets.only(left: 20, right: 20),
                      child: DefaultTextStyle(
                        style: const TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: 26,
                          height: 1.23,
                          color: Color.fromRGBO(51, 51, 51, 1),
                        ),
                        child: AnimatedTextKit(
                            totalRepeatCount: 1,
                            animatedTexts: [
                              TypewriterAnimatedText(
                                'Kai will create your MPC wallet via dual-entropy obfuscation algorithm',
                                curve: Curves.easeIn,
                                speed: Duration(milliseconds: 60),
                              ),
                            ],
                            onFinished: () {
                              _handleTap();
                              //   获取 算法
                              setLoadingIndex();
                            }),
                      ),
                    )))
          ],
        ),
        Stack(
          children: [
            Opacity(
              opacity: index > 3 ? 1 : 0, // 设置透明度值，范围从 0.0 到 1.0
              child: Container(
                padding: EdgeInsets.only(left: 20, right: 20),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Container(
                          child: Text(
                            'Successfully',
                            style: const TextStyle(
                              fontWeight: FontWeight.w600,
                              fontSize: 18,
                              height: 1.33,
                              color: Color.fromRGBO(193, 193, 193, 1),
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Container(
                          child: Text(
                            'Enhance Entropy',
                            style: const TextStyle(
                              fontWeight: FontWeight.w600,
                              fontSize: 18,
                              height: 1.33,
                              color: Color.fromRGBO(224, 217, 255, 1),
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: index <= 3 ? 40 : 20,
                    ),
                  ],
                ),
              ),
            ),
            Positioned(
                left: 0,
                top: 0,
                right: 0,
                child: Visibility(
                    visible: [1, 2, 3].contains(index),
                    child: Container(
                      padding: EdgeInsets.only(left: 20, right: 20),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              DefaultTextStyle(
                                style: const TextStyle(
                                  fontWeight: FontWeight.w600,
                                  fontSize: 26,
                                  height: 1.23,
                                  color: Color.fromRGBO(51, 51, 51, 1),
                                ),
                                child: AnimatedTextKit(
                                    totalRepeatCount: 1,
                                    animatedTexts: [
                                      TypewriterAnimatedText('Successfully',
                                          curve: Curves.easeIn,
                                          speed: Duration(milliseconds: 60)),
                                    ],
                                    onFinished: () {
                                      _handleTap();
                                    }),
                              ),
                              Visibility(
                                  visible: [2, 3].contains(index),
                                  child: DefaultTextStyle(
                                    style: const TextStyle(
                                      fontWeight: FontWeight.w600,
                                      fontSize: 26,
                                      height: 1.23,
                                      color: Color.fromRGBO(134, 103, 254, 1),
                                    ),
                                    child: AnimatedTextKit(
                                        totalRepeatCount: 1,
                                        animatedTexts: [
                                          TypewriterAnimatedText('Enhance',
                                              curve: Curves.easeIn,
                                              speed:
                                                  Duration(milliseconds: 60)),
                                        ],
                                        onFinished: () {
                                          _handleTap();
                                        }),
                                  )),
                            ],
                          ),
                          Visibility(
                              visible: index == 3,
                              child: Container(
                                child: DefaultTextStyle(
                                  style: const TextStyle(
                                    fontWeight: FontWeight.w600,
                                    fontSize: 26,
                                    height: 1.23,
                                    color: Color.fromRGBO(134, 103, 254, 1),
                                  ),
                                  child: AnimatedTextKit(
                                      totalRepeatCount: 1,
                                      animatedTexts: [
                                        TypewriterAnimatedText('Entropy',
                                            curve: Curves.easeIn,
                                            speed: Duration(milliseconds: 60)),
                                      ],
                                      onFinished: () {
                                        _handleTap();
                                        setLoadingIndex();
                                      }),
                                ),
                              )),
                        ],
                      ),
                    )))
          ],
        ),
        //  -0-------------------
        Stack(
          children: [
            Opacity(
              opacity: index > 6 ? 1 : 0, // 设置透明度值，范围从 0.0 到 1.0
              child: Container(
                padding: EdgeInsets.only(left: 20, right: 20),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Container(
                          child: Text(
                            'Successfully',
                            style: const TextStyle(
                              fontWeight: FontWeight.w600,
                              fontSize: 18,
                              height: 1.33,
                              color: Color.fromRGBO(193, 193, 193, 1),
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Container(
                          child: Text(
                            'Obfuscate Entropy',
                            style: const TextStyle(
                              fontWeight: FontWeight.w600,
                              fontSize: 18,
                              height: 1.33,
                              color: Color.fromRGBO(224, 217, 255, 1),
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: index <= 6 ? 40 : 20,
                    ),
                  ],
                ),
              ),
            ),
            Positioned(
                left: 0,
                top: 0,
                right: 0,
                child: Visibility(
                    visible: [4, 5, 6].contains(index),
                    child: Container(
                      padding: EdgeInsets.only(left: 20, right: 20),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              DefaultTextStyle(
                                style: const TextStyle(
                                  fontWeight: FontWeight.w600,
                                  fontSize: 26,
                                  height: 1.23,
                                  color: Color.fromRGBO(51, 51, 51, 1),
                                ),
                                child: AnimatedTextKit(
                                    totalRepeatCount: 1,
                                    animatedTexts: [
                                      TypewriterAnimatedText('Successfully',
                                          curve: Curves.easeIn,
                                          speed: Duration(milliseconds: 60)),
                                    ],
                                    onFinished: () {
                                      _handleTap();
                                    }),
                              ),
                              Visibility(
                                  visible: [5, 6].contains(index),
                                  child: DefaultTextStyle(
                                    style: const TextStyle(
                                      fontWeight: FontWeight.w600,
                                      fontSize: 26,
                                      height: 1.23,
                                      color: Color.fromRGBO(134, 103, 254, 1),
                                    ),
                                    child: AnimatedTextKit(
                                        totalRepeatCount: 1,
                                        animatedTexts: [
                                          TypewriterAnimatedText('Obfuscate',
                                              curve: Curves.easeIn,
                                              speed:
                                                  Duration(milliseconds: 60)),
                                        ],
                                        onFinished: () {
                                          _handleTap();
                                        }),
                                  )),
                            ],
                          ),
                          Visibility(
                              visible: index == 6,
                              child: Container(
                                child: DefaultTextStyle(
                                  style: const TextStyle(
                                    fontWeight: FontWeight.w600,
                                    fontSize: 26,
                                    height: 1.23,
                                    color: Color.fromRGBO(134, 103, 254, 1),
                                  ),
                                  child: AnimatedTextKit(
                                      totalRepeatCount: 1,
                                      animatedTexts: [
                                        TypewriterAnimatedText('Entropy',
                                            curve: Curves.easeIn,
                                            speed: Duration(milliseconds: 60)),
                                      ],
                                      onFinished: () {
                                        _handleTap();
                                        setLoadingIndex();
                                      }),
                                ),
                              )),
                        ],
                      ),
                    )))
          ],
        ),
        //-1-------------------
        Visibility(
            visible: index >= 7,
            child: Container(
              padding: EdgeInsets.only(left: 20, right: 20),
              child: Row(
                children: [
                  DefaultTextStyle(
                    style: const TextStyle(
                      fontWeight: FontWeight.w600,
                      fontSize: 26,
                      height: 1.23,
                      color: Color.fromRGBO(134, 103, 254, 1),
                    ),
                    child: AnimatedTextKit(
                        totalRepeatCount: 1,
                        animatedTexts: [
                          TypewriterAnimatedText('Private Key',
                              curve: Curves.easeIn,
                              speed: Duration(milliseconds: 60)),
                        ],
                        onFinished: () {
                          _handleTap();
                        }),
                  ),
                  Visibility(
                      visible: index >= 8,
                      child: DefaultTextStyle(
                        style: const TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: 26,
                          height: 1.23,
                          color: Color.fromRGBO(51, 51, 51, 1),
                        ),
                        child: AnimatedTextKit(
                            totalRepeatCount: 1,
                            animatedTexts: [
                              TypewriterAnimatedText('Sharding',
                                  curve: Curves.easeIn,
                                  speed: Duration(milliseconds: 60)),
                            ],
                            onFinished: () {
                              _handleTap();
                            }),
                      )),
                ],
              ),
            )),
        Visibility(
            visible: index >= 9,
            child: Container(
              padding: EdgeInsets.only(left: 20, right: 20),
              child: DefaultTextStyle(
                style: const TextStyle(
                  fontWeight: FontWeight.w600,
                  fontSize: 26,
                  height: 1.23,
                  color: Color.fromRGBO(51, 51, 51, 1),
                ),
                child: AnimatedTextKit(
                    totalRepeatCount: 1,
                    animatedTexts: [
                      TypewriterAnimatedText('Completed',
                          curve: Curves.easeIn,
                          speed: Duration(milliseconds: 60)),
                    ],
                    onFinished: () {
                      _handleTap();
                      setLoadingIndex();
                      if (widget.type == WalletCreationType.GENERATE){
                        initCreatedWallet();
                      }
                      if(widget.type == WalletCreationType.OVERWRITE){
                        initOverwriteWallet();
                      }
                      // if (widget.type == WalletCreationType.RECAST)
                      //   initRecastWallet();
                    }),
              ),
            )),
        Visibility(
            visible: index >= 10,
            child: Container(
              padding: EdgeInsets.only(left: 20, right: 20),
              child: DefaultTextStyle(
                style: const TextStyle(
                  fontWeight: FontWeight.w600,
                  fontSize: 26,
                  height: 1.23,
                  color: Color.fromRGBO(134, 103, 254, 1),
                ),
                child: AnimatedTextKit(repeatForever: true, animatedTexts: [
                  TypewriterAnimatedText(
                    '',
                    curve: Curves.easeIn,
                  ),
                ]),
              ),
            ))
      ],
    );
  }

  Widget recastWalletWidget() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const SizedBox(
          height: 70,
        ),
        Stack(
          children: [
            Opacity(
              opacity: index > 0 ? 1 : 0, // 设置透明度值，范围从 0.0 到 1.0
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    padding: EdgeInsets.only(left: 20, right: 20),
                    child: Text(
                      'Kai will create your MPC wallet via',
                      style: const TextStyle(
                        fontWeight: FontWeight.w600,
                        fontSize: 18,
                        height: 1.33,
                        color: Color.fromRGBO(193, 193, 193, 1),
                      ),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(left: 20, right: 20),
                    child: Text(
                      'dual-entropy obfuscation',
                      style: const TextStyle(
                        fontWeight: FontWeight.w600,
                        fontSize: 18,
                        height: 1.33,
                        color: Color.fromRGBO(193, 193, 193, 1),
                      ),
                    ),
                  ),
                  Container(
                    padding: EdgeInsets.only(left: 20, right: 20),
                    child: Text(
                      'algorithm',
                      style: const TextStyle(
                        fontWeight: FontWeight.w600,
                        fontSize: 18,
                        height: 1.33,
                        color: Color.fromRGBO(193, 193, 193, 1),
                      ),
                    ),
                  ),
                  SizedBox(
                    height: index == 0 ? 30 : 20,
                  ),
                ],
              ),
            ),
            Positioned(
                left: 0,
                top: 0,
                right: 0,
                bottom: 0,
                child: Visibility(
                    visible: index == 0,
                    child: Container(
                      padding: EdgeInsets.only(left: 20, right: 20),
                      child: DefaultTextStyle(
                        style: const TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: 26,
                          height: 1.23,
                          color: Color.fromRGBO(51, 51, 51, 1),
                        ),
                        child: AnimatedTextKit(
                            totalRepeatCount: 1,
                            animatedTexts: [
                              TypewriterAnimatedText(
                                'Kai will create your MPC wallet via dual-entropy obfuscation algorithm',
                                curve: Curves.easeIn,
                                speed: Duration(milliseconds: 60),
                              ),
                            ],
                            onFinished: () {
                              _handleTap();
                              //   获取 算法
                              setLoadingIndex();
                            }),
                      ),
                    )))
          ],
        ),
        Stack(
          children: [
            Opacity(
              opacity: index > 3 ? 1 : 0, // 设置透明度值，范围从 0.0 到 1.0
              child: Container(
                padding: EdgeInsets.only(left: 20, right: 20),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Container(
                          child: Text(
                            'Synthesize',
                            style: const TextStyle(
                              fontWeight: FontWeight.w600,
                              fontSize: 18,
                              height: 1.33,
                              color: Color.fromRGBO(224, 217, 255, 1),
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Container(
                          child: Text(
                            'the original fragments',
                            style: const TextStyle(
                              fontWeight: FontWeight.w600,
                              fontSize: 18,
                              height: 1.33,
                              color: Color.fromRGBO(193, 193, 193, 1),
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: index <= 3 ? 40 : 20,
                    ),
                  ],
                ),
              ),
            ),
            Positioned(
                left: 0,
                top: 0,
                right: 0,
                child: Visibility(
                    visible: [1, 2, 3].contains(index),
                    child: Container(
                      padding: EdgeInsets.only(left: 20, right: 20),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              DefaultTextStyle(
                                style: const TextStyle(
                                  fontWeight: FontWeight.w600,
                                  fontSize: 26,
                                  height: 1.23,
                                  color: Color.fromRGBO(134, 103, 254, 1),
                                ),
                                child: AnimatedTextKit(
                                    totalRepeatCount: 1,
                                    animatedTexts: [
                                      TypewriterAnimatedText('Synthesize',
                                          curve: Curves.easeIn,
                                          speed: Duration(milliseconds: 60)),
                                    ],
                                    onFinished: () {
                                      _handleTap();
                                    }),
                              ),
                              Visibility(
                                  visible: [2, 3].contains(index),
                                  child: DefaultTextStyle(
                                    style: const TextStyle(
                                      fontWeight: FontWeight.w600,
                                      fontSize: 26,
                                      height: 1.23,
                                      color: Color.fromRGBO(51, 51, 51, 1),
                                    ),
                                    child: AnimatedTextKit(
                                        totalRepeatCount: 1,
                                        animatedTexts: [
                                          TypewriterAnimatedText('the original',
                                              curve: Curves.easeIn,
                                              speed:
                                                  Duration(milliseconds: 60)),
                                        ],
                                        onFinished: () {
                                          _handleTap();
                                        }),
                                  )),
                            ],
                          ),
                          Visibility(
                              visible: index == 3,
                              child: Container(
                                child: DefaultTextStyle(
                                  style: const TextStyle(
                                    fontWeight: FontWeight.w600,
                                    fontSize: 26,
                                    height: 1.23,
                                    color: Color.fromRGBO(51, 51, 51, 1),
                                  ),
                                  child: AnimatedTextKit(
                                      totalRepeatCount: 1,
                                      animatedTexts: [
                                        TypewriterAnimatedText('fragments',
                                            curve: Curves.easeIn,
                                            speed: Duration(milliseconds: 60)),
                                      ],
                                      onFinished: () {
                                        _handleTap();
                                        setLoadingIndex();
                                      }),
                                ),
                              )),
                        ],
                      ),
                    )))
          ],
        ),
        Stack(
          children: [
            Opacity(
              opacity: index > 6 ? 1 : 0, // 设置透明度值，范围从 0.0 到 1.0
              child: Container(
                padding: EdgeInsets.only(left: 20, right: 20),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Container(
                          child: Text(
                            'Successfully',
                            style: const TextStyle(
                              fontWeight: FontWeight.w600,
                              fontSize: 18,
                              height: 1.33,
                              color: Color.fromRGBO(193, 193, 193, 1),
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Container(
                          child: Text(
                            'Enhance Entropy',
                            style: const TextStyle(
                              fontWeight: FontWeight.w600,
                              fontSize: 18,
                              height: 1.33,
                              color: Color.fromRGBO(224, 217, 255, 1),
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: index <= 6 ? 40 : 20,
                    ),
                  ],
                ),
              ),
            ),
            Positioned(
                left: 0,
                top: 0,
                right: 0,
                child: Visibility(
                    visible: [4, 5, 6].contains(index),
                    child: Container(
                      padding: EdgeInsets.only(left: 20, right: 20),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              DefaultTextStyle(
                                style: const TextStyle(
                                  fontWeight: FontWeight.w600,
                                  fontSize: 26,
                                  height: 1.23,
                                  color: Color.fromRGBO(51, 51, 51, 1),
                                ),
                                child: AnimatedTextKit(
                                    totalRepeatCount: 1,
                                    animatedTexts: [
                                      TypewriterAnimatedText('Successfully',
                                          curve: Curves.easeIn,
                                          speed: Duration(milliseconds: 60)),
                                    ],
                                    onFinished: () {
                                      _handleTap();
                                    }),
                              ),
                              Visibility(
                                  visible: [5, 6].contains(index),
                                  child: DefaultTextStyle(
                                    style: const TextStyle(
                                      fontWeight: FontWeight.w600,
                                      fontSize: 26,
                                      height: 1.23,
                                      color: Color.fromRGBO(134, 103, 254, 1),
                                    ),
                                    child: AnimatedTextKit(
                                        totalRepeatCount: 1,
                                        animatedTexts: [
                                          TypewriterAnimatedText('Enhance',
                                              curve: Curves.easeIn,
                                              speed:
                                                  Duration(milliseconds: 60)),
                                        ],
                                        onFinished: () {
                                          _handleTap();
                                        }),
                                  )),
                            ],
                          ),
                          Visibility(
                              visible: index == 6,
                              child: Container(
                                child: DefaultTextStyle(
                                  style: const TextStyle(
                                    fontWeight: FontWeight.w600,
                                    fontSize: 26,
                                    height: 1.23,
                                    color: Color.fromRGBO(134, 103, 254, 1),
                                  ),
                                  child: AnimatedTextKit(
                                      totalRepeatCount: 1,
                                      animatedTexts: [
                                        TypewriterAnimatedText('Entropy',
                                            curve: Curves.easeIn,
                                            speed: Duration(milliseconds: 60)),
                                      ],
                                      onFinished: () {
                                        _handleTap();
                                        setLoadingIndex();
                                      }),
                                ),
                              )),
                        ],
                      ),
                    )))
          ],
        ),
        //  -0-------------------
        Stack(
          children: [
            Opacity(
              opacity: index > 9 ? 1 : 0, // 设置透明度值，范围从 0.0 到 1.0
              child: Container(
                padding: EdgeInsets.only(left: 20, right: 20),
                child: Column(
                  children: [
                    Row(
                      children: [
                        Container(
                          child: Text(
                            'Successfully',
                            style: const TextStyle(
                              fontWeight: FontWeight.w600,
                              fontSize: 18,
                              height: 1.33,
                              color: Color.fromRGBO(193, 193, 193, 1),
                            ),
                          ),
                        ),
                        SizedBox(
                          width: 10,
                        ),
                        Container(
                          child: Text(
                            'Obfuscate Entropy',
                            style: const TextStyle(
                              fontWeight: FontWeight.w600,
                              fontSize: 18,
                              height: 1.33,
                              color: Color.fromRGBO(224, 217, 255, 1),
                            ),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: index <= 9 ? 40 : 20,
                    ),
                  ],
                ),
              ),
            ),
            Positioned(
                left: 0,
                top: 0,
                right: 0,
                child: Visibility(
                    visible: [7, 8, 9].contains(index),
                    child: Container(
                      padding: EdgeInsets.only(left: 20, right: 20),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              DefaultTextStyle(
                                style: const TextStyle(
                                  fontWeight: FontWeight.w600,
                                  fontSize: 26,
                                  height: 1.23,
                                  color: Color.fromRGBO(51, 51, 51, 1),
                                ),
                                child: AnimatedTextKit(
                                    totalRepeatCount: 1,
                                    animatedTexts: [
                                      TypewriterAnimatedText('Successfully',
                                          curve: Curves.easeIn,
                                          speed: Duration(milliseconds: 60)),
                                    ],
                                    onFinished: () {
                                      _handleTap();
                                    }),
                              ),
                              Visibility(
                                  visible: [8, 9].contains(index),
                                  child: DefaultTextStyle(
                                    style: const TextStyle(
                                      fontWeight: FontWeight.w600,
                                      fontSize: 26,
                                      height: 1.23,
                                      color: Color.fromRGBO(134, 103, 254, 1),
                                    ),
                                    child: AnimatedTextKit(
                                        totalRepeatCount: 1,
                                        animatedTexts: [
                                          TypewriterAnimatedText('Obfuscate',
                                              curve: Curves.easeIn,
                                              speed:
                                                  Duration(milliseconds: 60)),
                                        ],
                                        onFinished: () {
                                          _handleTap();
                                        }),
                                  )),
                            ],
                          ),
                          Visibility(
                              visible: index == 9,
                              child: Container(
                                child: DefaultTextStyle(
                                  style: const TextStyle(
                                    fontWeight: FontWeight.w600,
                                    fontSize: 26,
                                    height: 1.23,
                                    color: Color.fromRGBO(134, 103, 254, 1),
                                  ),
                                  child: AnimatedTextKit(
                                      totalRepeatCount: 1,
                                      animatedTexts: [
                                        TypewriterAnimatedText('Entropy',
                                            curve: Curves.easeIn,
                                            speed: Duration(milliseconds: 60)),
                                      ],
                                      onFinished: () {
                                        _handleTap();
                                        setLoadingIndex();
                                      }),
                                ),
                              )),
                        ],
                      ),
                    )))
          ],
        ),
        Visibility(
            visible: index >= 10,
            child: Container(
              padding: EdgeInsets.only(left: 20, right: 20),
              child: Row(
                children: [
                  DefaultTextStyle(
                    style: const TextStyle(
                      fontWeight: FontWeight.w600,
                      fontSize: 26,
                      height: 1.23,
                      color: Color.fromRGBO(134, 103, 254, 1),
                    ),
                    child: AnimatedTextKit(
                        totalRepeatCount: 1,
                        animatedTexts: [
                          TypewriterAnimatedText('Private Key',
                              curve: Curves.easeIn,
                              speed: Duration(milliseconds: 60)),
                        ],
                        onFinished: () {
                          _handleTap();
                        }),
                  ),
                  Visibility(
                      visible: index >= 11,
                      child: DefaultTextStyle(
                        style: const TextStyle(
                          fontWeight: FontWeight.w600,
                          fontSize: 26,
                          height: 1.23,
                          color: Color.fromRGBO(51, 51, 51, 1),
                        ),
                        child: AnimatedTextKit(
                            totalRepeatCount: 1,
                            animatedTexts: [
                              TypewriterAnimatedText('Sharding',
                                  curve: Curves.easeIn,
                                  speed: Duration(milliseconds: 60)),
                            ],
                            onFinished: () {
                              _handleTap();
                            }),
                      )),
                ],
              ),
            )),
        Visibility(
            visible: index >= 12,
            child: Container(
              padding: EdgeInsets.only(left: 20, right: 20),
              child: DefaultTextStyle(
                style: const TextStyle(
                  fontWeight: FontWeight.w600,
                  fontSize: 26,
                  height: 1.23,
                  color: Color.fromRGBO(51, 51, 51, 1),
                ),
                child: AnimatedTextKit(
                    totalRepeatCount: 1,
                    animatedTexts: [
                      TypewriterAnimatedText('Completed',
                          curve: Curves.easeIn,
                          speed: Duration(milliseconds: 60)),
                    ],
                    onFinished: () {
                      _handleTap();
                      setLoadingIndex();
                      initRecastWallet();
                    }),
              ),
            )),
        Visibility(
            visible: index >= 13,
            child: Container(
              padding: EdgeInsets.only(left: 20, right: 20),
              child: DefaultTextStyle(
                style: const TextStyle(
                  fontWeight: FontWeight.w600,
                  fontSize: 26,
                  height: 1.23,
                  color: Color.fromRGBO(134, 103, 254, 1),
                ),
                child: AnimatedTextKit(repeatForever: true, animatedTexts: [
                  TypewriterAnimatedText(
                    '',
                    curve: Curves.easeIn,
                  ),
                ]),
              ),
            ))
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    Widget currentContainer = widget.type != WalletCreationType.RECAST
        ? createWalletWidget()
        : recastWalletWidget();
    // TODO: implement build
    return Scaffold(
        backgroundColor: Colors.white,
        appBar: PageAssetsHeaderCom(
          WidgetLeft: Expanded(
            child: Padding(
              padding: EdgeInsets.only(left: 20.w, right: 20.w, top: 28.w),
              child: AnimatedBuilder(
                animation: _progressAnimation,
                builder: (context, child) {
                  return LinearProgressIndicator(
                    backgroundColor: Color.fromRGBO(224, 224, 224, 1),
                    valueColor: const AlwaysStoppedAnimation(
                        Color.fromRGBO(51, 51, 51, 1)),
                    value: _progressAnimation.value,
                    minHeight: 2,
                  );
                },
              ),
            ),
          ),
          WidgetRight: Container(),
        ),
        body: currentContainer,
        bottomNavigationBar: bottomNavigationBar());
  }
}
